package com.luoran.bartalks.core;

import java.util.concurrent.ConcurrentHashMap;

import org.springframework.util.StringUtils;

import com.luoran.bartalks.entity.biz.UserInfo;
import com.luoran.bartalks.utils.MD5;

/**
 * @author lifetime
 *
 */
public class AppUser {
	private static final ConcurrentHashMap<String, UserContextInfo> AppSessionCache = new ConcurrentHashMap<String, UserContextInfo>(100);
	private static ThreadLocal<UserContextInfo> local = new ThreadLocal<UserContextInfo>();
	
	/**
	 * @param userInfo
	 * @return accessToken
	 */
	static String put(UserInfo userInfo) {
		UserContextInfo info = new UserContextInfo();
		info.setId(userInfo.getString("id"));
		info.setLoginTime(System.currentTimeMillis());
		info.setNumber(userInfo.getLoginNo());
		info.setPwdMd5(userInfo.getLoginPwd());
		info.setCompanyId(userInfo.getCompanyId());
		info.setCompanyCode(userInfo.getCompanyCode());
		info.setCompanyName(userInfo.getCompanyName());
		info.setUserType(userInfo.getUserType());
		info.setAlias(userInfo.getNick());
		info.setAccessToken(MD5.get(info.getNumber() + info.getLoginTime() + info.getPwdMd5()));
		AppSessionCache.put(info.getAccessToken(), info);
		return info.getAccessToken();
	}

	/**
	 * @param number
	 * @param accessToken
	 * @return
	 */
	static boolean isValid(String accessToken) {
		if (StringUtils.isEmpty(accessToken)) {
			return false;
		}
		UserContextInfo info = get(accessToken);
		if (info != null) {
			return true;
		}
		return false;
	}

	static void clear(String number) {
		AppSessionCache.remove(number);
	}

	static UserContextInfo get(String accessToken) {
		return AppSessionCache.get(accessToken);
	}

	static void init(UserContextInfo contextInfo){
		local.set(contextInfo);
	}
	
	static void clear(){
		local.remove();
	}
	
	public static UserContextInfo get(){
		return local.get();
	}
	
}
